<?php

namespace App\Console\Commands\OpenShop;

use App\Library\FeiShu\SendFs;

use App\Service\OpenShop\Statistical\SignOrderStatisticalService;
use Guanguans\Notify\Factory;
use Illuminate\Console\Command;

class OpenShopOrderSignNewSignDaily extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'open_shop:order_sign_new_sign_daily {env=prod} {--day=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '每日签约 Family 数据推送 .';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $day = $this->option('day');
        $signOrderService = new SignOrderStatisticalService();

        if ($day) {
            $date = date('Y-m-d', strtotime($day));
        } else {
            $date = date('Y-m-d');
        }

        if (config('app.env') == 'qa' || config('app.env') == 'dev') {//测试用昨天日期
            $date = date('Y-m-d', strtotime("-1 day"));
        }

        $data = $signOrderService->getGyNewSignOrderRobotDataSource($date);

        $card = [
            'elements' => [
                [
                    "alt" => [
                        "content" => "",
                        "tag" => "plain_text"
                    ],
                    "img_key" => "img_v2_995bc13f-df64-404d-8c14-2e5b41644cag",
                    "tag" => "img"
                ]
            ],
            "header" => [
                "title" => [
                    "content" => "今日签约 $date",
                    "tag" => "plain_text"
                ]
            ]
        ];
        $data = collect($data);

        // 总数
        $totalCount = $data->sum('shopCountGySignRobot');
        if ($totalCount > 0) {
            $card['elements'] = array_merge($card['elements'], [
                [
                    "tag" => "markdown",
                    "content" => "**今日共 {$totalCount} 家**"
                ],

            ]);
        } else {
            return 0;
        }

        // 新签客户数
        $newSignOrderList = $data->where('typeGySignRobot', '新签客户')->sortBy('joinConsultantGySignRobot');

        if ($newSignOrderList->sum('shopCountGySignRobot') > 0) {
            $card['elements'] = array_merge($card['elements'], [
                [
                    "tag" => "hr",
                ],
                [
                    "tag" => "div",
                    "text" => [
                        "content" => " 🎉 **新签客户 {$newSignOrderList->sum('shopCountGySignRobot')} 家**",
                        "tag" => "lark_md"
                    ]
                ]
            ]);

            $newSignOrderTemp = '';
            foreach ($newSignOrderList as $signOrder) {
                $shortCity = self::getShortCityName($signOrder['provinceGySignRobot'],
                    $signOrder['cityGySignRobot']);
                $userName = self::getUserOpenIdTag($signOrder['joinConsultantGySignRobot']);
                $newSignOrderTemp .= "恭喜 {$userName} 签约 {$shortCity} 加盟商，授权{$signOrder['shopCountGySignRobot']}家店名额\n" . PHP_EOL;
            }
            $card['elements'] = array_merge($card['elements'], [
                [
                    "tag" => "div",
                    "text" => [
                        "content" => $newSignOrderTemp,
                        "tag" => "lark_md"
                    ],
                ],
            ]);
        }

        // 老加盟商裂变：N家
        $oldSignOrderList = $data->where('typeGySignRobot', '老店裂变')->sortBy('joinConsultantGySignRobot');
        if ($oldSignOrderList->sum('shopCountGySignRobot') > 0) {

            $card['elements'] = array_merge($card['elements'], [
                [
                    "tag" => "hr",
                ],
                [
                    "tag" => "div",
                    "text" => [
                        "content" => " 🎉 **老加盟商裂变 {$oldSignOrderList->sum('shopCountGySignRobot')} 家**",
                        "tag" => "lark_md"
                    ]
                ]
            ]);

            $oldSignOrderTemp = '';
            foreach ($oldSignOrderList as $signOrder) {
                $shortCity = self::getShortCityName($signOrder['provinceGySignRobot'],
                    $signOrder['cityGySignRobot']);
                $userName = self::getUserOpenIdTag($signOrder['joinConsultantGySignRobot']);
                if ($userName && $signOrder['joinConsultantGySignRobot']) {//签约明细中老加盟商裂变增加对应推荐人（如果存在）
                    $oldSignOrderTemp .= "恭喜  {$userName}  裂变 {$shortCity} 加盟商，授权{$signOrder['shopCountGySignRobot']}家店名额\n" . PHP_EOL;
                } else {
                    $oldSignOrderTemp .= "恭喜 {$shortCity} 加盟商裂变{$signOrder['shopCountGySignRobot']}家店\n" . PHP_EOL;
                }
            }
            $card['elements'] = array_merge($card['elements'], [
                [
                    "tag" => "div",
                    "text" => [
                        "content" => $oldSignOrderTemp,
                        "tag" => "lark_md"
                    ],
                ],
            ]);
        }

        // 员工开店：N家
        $workerSignOrderList = $data->where('typeGySignRobot', '员工开店')->sortBy('joinConsultantGySignRobot');
        if ($workerSignOrderList->sum('shopCountGySignRobot') > 0) {
            $card['elements'] = array_merge($card['elements'], [
                [
                    "tag" => "hr",
                ],
                [
                    "tag" => "div",
                    "text" => [
                        "content" => " 🎉 **员工开店 {$workerSignOrderList->sum('shopCountGySignRobot')} 家**",
                        "tag" => "lark_md"
                    ]
                ]
            ]);

            $workSignOrderTemp = '';
            foreach ($workerSignOrderList as $signOrder) {
                $shortCity = self::getShortCityName($signOrder['provinceGySignRobot'],
                    $signOrder['cityGySignRobot']);
                $workSignOrderTemp .= "恭喜 夸父员工 在 {$shortCity} 开设 {$signOrder['shopCountGySignRobot']}家店\n" . PHP_EOL;
            }

            $card['elements'] = array_merge($card['elements'], [
                [
                    "tag" => "div",
                    "text" => [
                        "content" => $workSignOrderTemp,
                        "tag" => "lark_md"
                    ],
                ],
            ]);
        }
        //查询当月招商个人和团队信息
        $startTime = date('Y-m-01');//本月1号
        $orderSignContractData = $signOrderService->getPersonalAndTeamData($startTime);//获取优秀个人和团队数据

        if ($orderSignContractData && $orderSignContractData['personal'] && $orderSignContractData['team']) {
            //  1. 【全员招商】优秀个人
            $card['elements'] = array_merge(
                $card['elements'], [
                    [
                        "tag" => "hr",
                    ],
                    [
                        "tag" => "markdown",
                        "content" => "**【全员招商】优秀个人**"
                    ],
                    [
                        "tag" => "column_set",
                        "flex_mode" => "none",
                        "background_style" => "grey",
                        "columns" => [
                            [
                                "tag" => "column",
                                "width" => "weighted",
                                "weight" => 1,
                                "vertical_align" => "top",
                                "elements" => [
                                    [
                                        "tag" => "markdown",
                                        "content" => "**签约人**",
                                        "text_align" => "center",
                                    ]
                                ]
                            ],
                            [
                                "tag" => "column",
                                "width" => "weighted",
                                "weight" => 1,
                                "vertical_align" => "top",
                                "elements" => [
                                    [
                                        "tag" => "markdown",
                                        "content" => "**分公司**",
                                        "text_align" => "center",
                                    ]
                                ]
                            ],
                            [
                                "tag" => "column",
                                "width" => "weighted",
                                "weight" => 1,
                                "vertical_align" => "top",
                                "elements" => [
                                    [
                                        "tag" => "markdown",
                                        "content" => "**裂变**",
                                        "text_align" => "center",
                                    ]
                                ]
                            ],
                            [
                                "tag" => "column",
                                "width" => "weighted",
                                "weight" => 1,
                                "vertical_align" => "top",
                                "elements" => [
                                    [
                                        "tag" => "markdown",
                                        "content" => "**拉新**",
                                        "text_align" => "center",
                                    ]
                                ]
                            ],
                            [
                                "tag" => "column",
                                "width" => "weighted",
                                "weight" => 1,
                                "vertical_align" => "top",
                                "elements" => [
                                    [
                                        "tag" => "markdown",
                                        "content" => "**总数**",
                                        "text_align" => "center",
                                    ]
                                ]
                            ],
                        ],
                    ],
                ]
            );
            foreach ($orderSignContractData['personal'] as $v) {
                $card['elements'] = array_merge(
                    $card['elements'],
                    [
                        [
                            "tag" => "column_set",
                            "flex_mode" => "none",
                            "background_style" => "default",
                            "columns" => [
                                [
                                    "tag" => "column",
                                    "width" => "weighted",
                                    "weight" => 1,
                                    "vertical_align" => "top",
                                    "elements" => [
                                        [
                                            "tag" => "markdown",
                                            "content" => "{$v['inviterName']}",
                                            "text_align" => "center",
                                        ]
                                    ]
                                ],
                                [
                                    "tag" => "column",
                                    "width" => "weighted",
                                    "weight" => 1,
                                    "vertical_align" => "top",
                                    "elements" => [
                                        [
                                            "tag" => "markdown",
                                            "content" => "{$v['departmentName']}",
                                            "text_align" => "center",
                                        ]
                                    ]
                                ], [
                                    "tag" => "column",
                                    "width" => "weighted",
                                    "weight" => 1,
                                    "vertical_align" => "top",
                                    "elements" => [
                                        [
                                            "tag" => "markdown",
                                            "content" => "{$v['fission']}",
                                            "text_align" => "center",
                                        ]
                                    ]
                                ],
                                [
                                    "tag" => "column",
                                    "width" => "weighted",
                                    "weight" => 1,
                                    "vertical_align" => "top",
                                    "elements" => [
                                        [
                                            "tag" => "markdown",
                                            "content" => "{$v['new']}",
                                            "text_align" => "center",
                                        ]
                                    ]
                                ], [
                                    "tag" => "column",
                                    "width" => "weighted",
                                    "weight" => 1,
                                    "vertical_align" => "top",
                                    "elements" => [
                                        [
                                            "tag" => "markdown",
                                            "content" => "{$v['total']}",
                                            "text_align" => "center",
                                        ]
                                    ]
                                ],
                            ]
                        ],
                    ]
                );
            }

            //  2. 【全员招商】优秀团队
            $card['elements'] = array_merge(
                $card['elements'], [
                    [
                        "tag" => "hr",
                    ],
                    [
                        "tag" => "markdown",
                        "content" => "**【全员招商】优秀团队**"
                    ],
                    [
                        "tag" => "column_set",
                        "flex_mode" => "none",
                        "background_style" => "grey",
                        "columns" => [
                            [
                                "tag" => "column",
                                "width" => "weighted",
                                "weight" => 1,
                                "vertical_align" => "top",
                                "elements" => [
                                    [
                                        "tag" => "markdown",
                                        "content" => "**分公司**",
                                        "text_align" => "center",
                                    ]
                                ]
                            ],
                            [
                                "tag" => "column",
                                "width" => "weighted",
                                "weight" => 1,
                                "vertical_align" => "top",
                                "elements" => [
                                    [
                                        "tag" => "markdown",
                                        "content" => "**裂变**",
                                        "text_align" => "center",
                                    ]
                                ]
                            ],
                            [
                                "tag" => "column",
                                "width" => "weighted",
                                "weight" => 1,
                                "vertical_align" => "top",
                                "elements" => [
                                    [
                                        "tag" => "markdown",
                                        "content" => "**拉新**",
                                        "text_align" => "center",
                                    ]
                                ]
                            ],
                            [
                                "tag" => "column",
                                "width" => "weighted",
                                "weight" => 1,
                                "vertical_align" => "top",
                                "elements" => [
                                    [
                                        "tag" => "markdown",
                                        "content" => "**总数**",
                                        "text_align" => "center",
                                    ]
                                ]
                            ],
                        ],
                    ],
                ]
            );

            foreach ($orderSignContractData['team'] as $v) {
                $card['elements'] = array_merge(
                    $card['elements'],
                    [
                        [
                            "tag" => "column_set",
                            "flex_mode" => "none",
                            "background_style" => "default",
                            "columns" => [
                                [
                                    "tag" => "column",
                                    "width" => "weighted",
                                    "weight" => 1,
                                    "vertical_align" => "top",
                                    "elements" => [
                                        [
                                            "tag" => "markdown",
                                            "content" => "{$v['departmentName']}",
                                            "text_align" => "center",
                                        ]
                                    ]
                                ], [
                                    "tag" => "column",
                                    "width" => "weighted",
                                    "weight" => 1,
                                    "vertical_align" => "top",
                                    "elements" => [
                                        [
                                            "tag" => "markdown",
                                            "content" => "{$v['fission']}",
                                            "text_align" => "center",
                                        ]
                                    ]
                                ],
                                [
                                    "tag" => "column",
                                    "width" => "weighted",
                                    "weight" => 1,
                                    "vertical_align" => "top",
                                    "elements" => [
                                        [
                                            "tag" => "markdown",
                                            "content" => "{$v['new']}",
                                            "text_align" => "center",
                                        ]
                                    ]
                                ], [
                                    "tag" => "column",
                                    "width" => "weighted",
                                    "weight" => 1,
                                    "vertical_align" => "top",
                                    "elements" => [
                                        [
                                            "tag" => "markdown",
                                            "content" => "{$v['total']}",
                                            "text_align" => "center",
                                        ]
                                    ]
                                ],
                            ]
                        ],
                    ]
                );
            }
        }

        if ($this->isProd()) {
            $card['elements'] = array_merge($card['elements'], [
                [
                    "tag" => "hr",
                ],
                [
                    "tag" => "div",
                    "text" => [
                        "content" => "<at id=all></at",
                        "tag" => "lark_md"
                    ]
                ]
            ]);
        }

        $robot = self::getRobot();
        Factory::feiShu()
            ->setToken($robot['urlToken'])
            ->setSecret($robot['secret'])
            ->setMessage(new \Guanguans\Notify\Messages\FeiShu\CardMessage($card))
            ->send();
    }

    private function isProd()
    {
        if ('prod' == $this->argument('env') && config('app.env') == 'prod') {
            return true;
        } else {
            return false;
        }
    }

    private function getShortCityName(string $str1, string $str2)
    {
        if ($str1 == $str2) {
            $result = $str1;
        } else {
            $result = $str1 . ' ' . $str2;
        }

        $result = "$result";
        return $result;
    }

    private function getRobot()
    {
        if ($this->isProd()) {
            return [
                'url' => 'https://open.feishu.cn/open-apis/bot/v2/hook/676d6a0c-eb9d-4f96-9eb9-5b5da8b688df',
                'urlToken' => '676d6a0c-eb9d-4f96-9eb9-5b5da8b688df',
                'secret' => 'gNz7El3QuJ8Q4Qujp1aPhb'
            ];
        } else {
            return [
                'url' => 'https://open.feishu.cn/open-apis/bot/v2/hook/e987d7bc-f95a-4bdb-a2bd-6b2da85b1890',
                'urlToken' => 'e987d7bc-f95a-4bdb-a2bd-6b2da85b1890',
                'secret' => 'U1GmtypahojK33wwNMf5lb'
            ];
        }
    }

    private function getUserOpenIdTag($userName)
    {
        return $userName;
        /*$userOpenIdMap = [
//            '冯亭亭（静音）' => 'ou_27a082615205ea874d2e3c27fc7960db'
        ];

        if (!empty($userOpenIdMap[$userName])) {
            return "<at id=$userOpenIdMap[$userName]></at>";
        } else {
            return "<at id>$userName</at>";
        }*/
    }


}
